#!/bin/bash

# 自适应光源算法模块安装脚本
# 适用于香橙派3B (Ubuntu/Debian系统)
# IPCS 2025电赛培训项目

echo "=========================================="
echo "  自适应光源算法模块安装脚本"
echo "  IPCS 2025电赛培训项目"
echo "=========================================="

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查是否为root用户
check_root() {
    if [ "$EUID" -eq 0 ]; then
        log_warning "建议不要使用root用户运行此脚本"
        read -p "是否继续？(y/n): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            exit 1
        fi
    fi
}

# 检查系统架构
check_system() {
    log_info "检查系统信息..."
    
    # 检查操作系统
    if [[ "$OSTYPE" == "linux-gnu"* ]]; then
        OS="Linux"
        log_success "操作系统: $OS"
    else
        log_error "不支持的操作系统: $OSTYPE"
        exit 1
    fi
    
    # 检查架构
    ARCH=$(uname -m)
    log_success "系统架构: $ARCH"
    
    # 检查Python版本
    if command -v python3 &> /dev/null; then
        PYTHON_VERSION=$(python3 --version | cut -d' ' -f2)
        log_success "Python版本: $PYTHON_VERSION"
        
        # 检查Python版本是否>=3.8
        if python3 -c "import sys; exit(0 if sys.version_info >= (3, 8) else 1)"; then
            log_success "Python版本满足要求 (>=3.8)"
        else
            log_error "Python版本过低，需要3.8或更高版本"
            exit 1
        fi
    else
        log_error "未找到Python3，请先安装Python3"
        exit 1
    fi
}

# 更新系统包
update_system() {
    log_info "更新系统包列表..."
    
    if command -v apt &> /dev/null; then
        sudo apt update
        log_success "系统包列表更新完成"
    elif command -v yum &> /dev/null; then
        sudo yum update
        log_success "系统包列表更新完成"
    else
        log_warning "未识别的包管理器，请手动更新系统"
    fi
}

# 安装系统依赖
install_system_deps() {
    log_info "安装系统依赖包..."
    
    DEPS="python3-pip python3-dev python3-opencv libopencv-dev cmake build-essential"
    DEPS="$DEPS libgtk-3-dev libavcodec-dev libavformat-dev libswscale-dev"
    DEPS="$DEPS libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev"
    DEPS="$DEPS libv4l-dev libxvidcore-dev libx264-dev libjpeg-dev libpng-dev"
    DEPS="$DEPS libtiff-dev gfortran openexr libatlas-base-dev libssl-dev"
    
    if command -v apt &> /dev/null; then
        sudo apt install -y $DEPS
        
        # 安装串口相关包
        sudo apt install -y setserial
        
        log_success "系统依赖包安装完成"
    else
        log_error "请手动安装以下依赖包: $DEPS"
        exit 1
    fi
}

# 安装Python依赖
install_python_deps() {
    log_info "安装Python依赖包..."
    
    # 升级pip
    python3 -m pip install --upgrade pip
    
    # 安装核心依赖
    PYTHON_DEPS="opencv-python opencv-contrib-python numpy pyserial matplotlib"
    PYTHON_DEPS="$PYTHON_DEPS dataclasses typing-extensions"
    
    python3 -m pip install $PYTHON_DEPS
    
    if [ $? -eq 0 ]; then
        log_success "Python依赖包安装完成"
    else
        log_error "Python依赖包安装失败"
        exit 1
    fi
    
    # 验证安装
    log_info "验证Python包安装..."
    python3 -c "import cv2, numpy, serial; print('核心包导入成功')" || {
        log_error "Python包验证失败"
        exit 1
    }
    log_success "Python包验证通过"
}

# 配置串口权限
setup_serial_permissions() {
    log_info "配置串口权限..."
    
    # 添加用户到dialout组
    sudo usermod -a -G dialout $USER
    
    # 创建udev规则文件
    UDEV_RULE="/etc/udev/rules.d/99-orange-pi-serial.rules"
    
    sudo tee $UDEV_RULE > /dev/null << EOF
# Orange Pi Serial Port Rules
# USB转串口设备
SUBSYSTEM=="tty", ATTRS{idVendor}=="1a86", ATTRS{idProduct}=="7523", GROUP="dialout", MODE="0666"
SUBSYSTEM=="tty", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6001", GROUP="dialout", MODE="0666"

# 通用串口设备
KERNEL=="ttyUSB*", GROUP="dialout", MODE="0666"
KERNEL=="ttyACM*", GROUP="dialout", MODE="0666"
EOF

    # 重新加载udev规则
    sudo udevadm control --reload-rules
    sudo udevadm trigger
    
    log_success "串口权限配置完成"
    log_warning "需要重新登录以使权限生效"
}

# 配置摄像头权限
setup_camera_permissions() {
    log_info "配置摄像头权限..."
    
    # 添加用户到video组
    sudo usermod -a -G video $USER
    
    # 创建摄像头udev规则
    CAMERA_UDEV_RULE="/etc/udev/rules.d/99-orange-pi-camera.rules"
    
    sudo tee $CAMERA_UDEV_RULE > /dev/null << EOF
# Orange Pi Camera Rules
# USB摄像头设备
SUBSYSTEM=="video4linux", GROUP="video", MODE="0666"
KERNEL=="video*", GROUP="video", MODE="0666"
EOF

    # 重新加载udev规则
    sudo udevadm control --reload-rules
    sudo udevadm trigger
    
    log_success "摄像头权限配置完成"
}

# 创建项目目录结构
create_project_structure() {
    log_info "创建项目目录结构..."
    
    PROJECT_DIR="$HOME/IPCS_adaptive_light"
    
    mkdir -p $PROJECT_DIR/{src,config,logs,debug_output,docs}
    
    # 创建软链接到当前目录的模块文件
    if [ -f "adaptive_light_algorithm.py" ]; then
        cp adaptive_light_algorithm.py $PROJECT_DIR/src/
        log_success "已复制主模块文件"
    fi
    
    if [ -f "config.py" ]; then
        cp config.py $PROJECT_DIR/config/
        log_success "已复制配置文件"
    fi
    
    if [ -f "test_adaptive_light.py" ]; then
        cp test_adaptive_light.py $PROJECT_DIR/src/
        log_success "已复制测试文件"
    fi
    
    # 创建启动脚本
    cat > $PROJECT_DIR/run_test.sh << 'EOF'
#!/bin/bash
cd "$(dirname "$0")/src"
python3 test_adaptive_light.py
EOF
    chmod +x $PROJECT_DIR/run_test.sh
    
    log_success "项目目录结构创建完成: $PROJECT_DIR"
}

# 测试硬件连接
test_hardware() {
    log_info "测试硬件连接..."
    
    # 测试摄像头
    if [ -e "/dev/video0" ]; then
        log_success "检测到摄像头设备: /dev/video0"
        
        # 简单的摄像头测试
        python3 -c "
import cv2
cap = cv2.VideoCapture(0)
if cap.isOpened():
    print('摄像头连接正常')
    cap.release()
else:
    print('摄像头连接失败')
    exit(1)
" && log_success "摄像头测试通过" || log_warning "摄像头测试失败"
    else
        log_warning "未检测到摄像头设备"
    fi
    
    # 测试串口
    if ls /dev/ttyUSB* 1> /dev/null 2>&1; then
        SERIAL_DEVICES=$(ls /dev/ttyUSB*)
        log_success "检测到串口设备: $SERIAL_DEVICES"
    elif ls /dev/ttyACM* 1> /dev/null 2>&1; then
        SERIAL_DEVICES=$(ls /dev/ttyACM*)
        log_success "检测到串口设备: $SERIAL_DEVICES"
    else
        log_warning "未检测到串口设备"
    fi
}

# 创建系统服务 (可选)
create_service() {
    read -p "是否创建系统服务以自动启动？(y/n): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        log_info "创建系统服务..."
        
        SERVICE_FILE="/etc/systemd/system/adaptive-light.service"
        
        sudo tee $SERVICE_FILE > /dev/null << EOF
[Unit]
Description=Adaptive Light Algorithm Service
After=network.target

[Service]
Type=simple
User=$USER
WorkingDirectory=$HOME/IPCS_adaptive_light/src
ExecStart=/usr/bin/python3 adaptive_light_algorithm.py
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

        sudo systemctl daemon-reload
        sudo systemctl enable adaptive-light.service
        
        log_success "系统服务创建完成"
        log_info "使用以下命令控制服务:"
        echo "  启动: sudo systemctl start adaptive-light"
        echo "  停止: sudo systemctl stop adaptive-light"
        echo "  状态: sudo systemctl status adaptive-light"
    fi
}

# 生成配置文件
generate_config() {
    log_info "生成默认配置文件..."
    
    CONFIG_DIR="$HOME/IPCS_adaptive_light/config"
    
    # 检测摄像头
    CAMERA_INDEX=0
    if [ -e "/dev/video1" ]; then
        CAMERA_INDEX=1
    fi
    
    # 检测串口
    UART_PORT="/dev/ttyUSB0"
    if [ -e "/dev/ttyACM0" ]; then
        UART_PORT="/dev/ttyACM0"
    elif [ -e "/dev/ttyUSB1" ]; then
        UART_PORT="/dev/ttyUSB1"
    fi
    
    # 创建自动配置文件
    cat > $CONFIG_DIR/auto_config.py << EOF
# 自动生成的配置文件
# 基于硬件检测结果

# 摄像头配置
CAMERA_INDEX = $CAMERA_INDEX
UART_PORT = "$UART_PORT"

# 系统特定配置
import os
HOME_DIR = os.path.expanduser("~")
PROJECT_DIR = os.path.join(HOME_DIR, "IPCS_adaptive_light")
DEBUG_OUTPUT_DIR = os.path.join(PROJECT_DIR, "debug_output")
LOG_DIR = os.path.join(PROJECT_DIR, "logs")

# 性能配置 (针对香橙派优化)
PERFORMANCE_OPTIMIZED = True
REDUCED_RESOLUTION = True
CAMERA_WIDTH = 1280 if not REDUCED_RESOLUTION else 640
CAMERA_HEIGHT = 720 if not REDUCED_RESOLUTION else 480
CAMERA_FPS = 15  # 降低帧率以提高稳定性
EOF

    log_success "配置文件生成完成"
}

# 安装完成后的清理和建议
post_install() {
    log_info "安装后配置..."
    
    # 创建桌面快捷方式
    DESKTOP_FILE="$HOME/Desktop/adaptive_light_test.desktop"
    cat > $DESKTOP_FILE << EOF
[Desktop Entry]
Version=1.0
Type=Application
Name=自适应光源算法测试
Comment=IPCS 2025电赛培训项目
Exec=gnome-terminal -- bash -c "cd $HOME/IPCS_adaptive_light && ./run_test.sh; exec bash"
Icon=camera-video
Terminal=false
Categories=Development;
EOF
    chmod +x $DESKTOP_FILE
    
    log_success "桌面快捷方式创建完成"
    
    # 创建说明文档
    cat > $HOME/IPCS_adaptive_light/INSTALL_INFO.txt << EOF
自适应光源算法模块安装信息
========================================

安装时间: $(date)
项目目录: $HOME/IPCS_adaptive_light
摄像头设备: /dev/video$CAMERA_INDEX
串口设备: $UART_PORT

重要提醒:
1. 需要重新登录以使权限生效
2. 确保摄像头和串口设备已正确连接
3. 运行测试前请检查硬件连接

使用方法:
- 运行测试: cd $HOME/IPCS_adaptive_light && ./run_test.sh
- 查看文档: cat $HOME/IPCS_adaptive_light/docs/README.md
- 修改配置: nano $HOME/IPCS_adaptive_light/config/config.py

故障排除:
- 摄像头问题: ls -l /dev/video*
- 串口问题: ls -l /dev/tty*
- 权限问题: groups \$USER
- 日志查看: tail -f $HOME/IPCS_adaptive_light/logs/*.log

技术支持:
IPCS 2025电赛培训项目组
EOF

    log_success "安装信息文件创建完成"
}

# 显示安装结果
show_install_summary() {
    echo
    echo "=========================================="
    echo -e "${GREEN}        安装完成！${NC}"
    echo "=========================================="
    echo
    log_success "项目目录: $HOME/IPCS_adaptive_light"
    log_success "测试脚本: $HOME/IPCS_adaptive_light/run_test.sh"
    log_success "配置文件: $HOME/IPCS_adaptive_light/config/"
    log_success "桌面快捷方式已创建"
    echo
    echo -e "${YELLOW}重要提醒:${NC}"
    echo "1. ${RED}请重新登录${NC}以使串口和摄像头权限生效"
    echo "2. 确保USB摄像头已连接"
    echo "3. 确保STM32开发板已通过串口连接"
    echo
    echo -e "${BLUE}快速开始:${NC}"
    echo "cd $HOME/IPCS_adaptive_light"
    echo "./run_test.sh"
    echo
    echo -e "${BLUE}或者点击桌面上的快捷方式${NC}"
    echo
}

# 主安装流程
main() {
    echo "开始安装..."
    echo
    
    # 检查root权限
    check_root
    
    # 系统检查
    check_system
    
    # 更新系统
    read -p "是否更新系统包？(y/n): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        update_system
    fi
    
    # 安装依赖
    install_system_deps
    install_python_deps
    
    # 配置权限
    setup_serial_permissions
    setup_camera_permissions
    
    # 创建项目结构
    create_project_structure
    
    # 生成配置
    generate_config
    
    # 测试硬件
    test_hardware
    
    # 创建服务(可选)
    create_service
    
    # 安装后配置
    post_install
    
    # 显示结果
    show_install_summary
}

# 脚本入口点
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi
        